package com.yuoj.yuojbackendjudgeservice.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.yuoj.backendcommon.common.ErrorCode;
import com.yuoj.backendcommon.exception.BusinessException;
import lombok.SneakyThrows;


/**
 * @author 刘渠好
 * @since 2025-04-16 21:52
 * 用于创建交换机和队列
 */
public class MqInitMain {


    @SneakyThrows
    public static void init() {
        ConnectionFactory factory = new ConnectionFactory ();
        Channel channel = null;
        try(Connection connection=factory.newConnection ()){
            factory.setHost("localhost");
            /**
             * channel好比是jdbc，是操作rabbitmq的客户端（比如：redisClient，DockerClient）
             */
            channel = connection.createChannel (); //操作消息队列的客户端
            String exchangeName="code_exchange";  //交换机
            channel.exchangeDeclare (exchangeName,"direct");  //声明一个交换机

            //创建队列
            String queueName="code_queue";
            channel.queueDeclare (queueName,true,false,false,null); //声明一个队列
            channel.queueBind (queueName,exchangeName,"my_routingKey"); //队列和交换机进行绑定
        } catch (Exception e) {
            throw new BusinessException (ErrorCode.PARAMS_ERROR,"rabbitmq init failed!");
        }finally {
            assert channel != null;
            channel.close ();
        }
    }
}
